package oakclub.service;

import oakclub.global.Json;
import oakclub.utility.HttpUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GoogleService
{
    private final Logger logger = LoggerFactory.getLogger(GoogleService.class);

    private final String URL_GOOGLE_GEO = "http://maps.google.com/maps/api/geocode/json";

    public String getCountryCode(double latitude, double longitude)
    {
        try
        {
            // send request
            Map<String, Object> params = new HashMap<>();
            params.put("latlng", "" + latitude + ',' + longitude);
            params.put("sensor", false);
            String response = HttpUtility.sendGet(this.URL_GOOGLE_GEO, params);

            // parse response
            Map<String, Object> root = Json.getParser().fromJson(response, Map.class);
            List<Object> results = (List<Object>) root.get("results");
            Map<String, Object> result = (Map<String, Object>) results.get(0);
            List<Object> addressComponents = (List<Object>) result.get("address_components");
            for(Object element : addressComponents)
            {
                Map<String, Object> addressComponent = (Map<String, Object>) element;
                List<Object> types = (List<Object>) addressComponent.get("types");
                if(types.contains("country"))
                {
                    String countryCode = (String) addressComponent.get("short_name");
                    return countryCode;
                }
            }
        }
        catch(Exception e)
        {
            logger.warn("google geo issue", e);
        }

        return null;
    }
}
